from django.contrib.auth.hashers import make_password
from django.db import models
from django.conf import settings

# Create your models here.


class User(models.Model):
    username = models.CharField(max_length=32, verbose_name="用户名")
    password = models.CharField(max_length=255, verbose_name="密码")
    phone = models.CharField(max_length=11, verbose_name="电话")
    # {"address": "南山", age: 18}
    detail = models.JSONField(verbose_name="用户详情")

    class Meta:
        db_table = "user"
        verbose_name = "用户表"
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.username

    def save(self, force_insert=False, force_update=False, using=None,
             update_fields=None):
        self.password = make_password(self.password, settings.SECRET_KEY)
        return super().save()

    def to_dict(self):
        return {
            "id": self.id,
            "username": self.username,
            "phone": self.phone,
            "detail": self.detail
        }


class Post(models.Model):
    title = models.CharField(max_length=100, verbose_name="标题")
    content = models.TextField(verbose_name="内容")
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="posts", verbose_name="作者")

    class Meta:
        db_table = "post"
        verbose_name = "文章表"
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.title

    def to_dict(self):
        return {
            "id": self.id,
            "title": self.title,
            "content": self.content,
            "user_id": self.user_id
        }
